<template>
	<div class="pay" v-loading="loading">
		<div class="pay-content">
			<div class="qrcode" id="qrcode"></div>
			<div class="pay-text">
				<p>请使用微信“扫一扫”</p>
				<p>扫描二维码支付</p>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		wxPay,
		pcCheckPay
	} from "@/api/apiList/user.js"
	import QRCode from 'qrcodejs2' //引入方法
	export default {
		name:"pay",
		props: {
			id: { //我的报考id
				type: String,
				required: true
			}
		},
		data() {
			return {
				codeUrl: "",
				timer: null,
				loading:false
			}
		},
		methods: {
			async API_wxPay(id) { //微信支付
				let result = {
					param: {
						id,
						app: 2 //1-小程序、2-pc
					}
				}
				return await wxPay(result)
			},
			async API_pcCheckPay(id) { //微信支付查询
				let result = {
					param: {
						id
					}
				}
				return await pcCheckPay(result)
			},
			createCode(url) { //根据codeUrl生成微信二维码
				new QRCode(document.getElementById("qrcode"), url);
			},
			timeHandler() { //定时器
				this.timer = setInterval(async () => {
					let res = await this.API_pcCheckPay(this.id)
					console.log(res)
					if (res.data.code === 1000) {
						this.$message({
							message: res.data.msg,
							type: 'success'
						});
						this.$router.replace("/signup")
					}
				}, 3000)
			}
		},
		async created() {
			this.loading = true
			let res = await this.API_wxPay(this.id)
			
			this.codeUrl = res.data.data.codeUrl
			this.createCode(this.codeUrl)

			clearInterval(this.timer) //进入页面先清空计时器再开始计时
			this.timeHandler()
			this.loading = false
		},
		beforeDestroy() {
			clearInterval(this.timer) //离开的时候要清空计时器
			this.timer = null
		}
	}
</script>

<style lang="scss" scoped>
	.pay{
		display: flex;
		width: 100%;
		height: 100%;
		justify-content: center;
		align-items: center;
		.pay-content{
			.pay-text{
				margin-top: 10px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
			}
		}
	}
</style>
